package com.gykfbxxh.imovie.view.filmsdetail.acitivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.gykfbxxh.imovie.R;
import com.gykfbxxh.imovie.base.BaseActivity;
import com.gykfbxxh.imovie.bean.comment.FilmComment;
import com.gykfbxxh.imovie.bean.film.FilmDetailInfo;
import com.gykfbxxh.imovie.bean.news.ShareBean;
import com.gykfbxxh.imovie.config.URIContant;
import com.gykfbxxh.imovie.custom.view.LoadView;
import com.gykfbxxh.imovie.listener.CommentListener;
import com.gykfbxxh.imovie.listener.HttpListener;
import com.gykfbxxh.imovie.manager.AppManager;
import com.gykfbxxh.imovie.utils.AppShareUtils;
import com.gykfbxxh.imovie.utils.CommentUtils;
import com.gykfbxxh.imovie.utils.HttpUtils;
import com.gykfbxxh.imovie.view.filmsdetail.view.CommentListView;
import com.gykfbxxh.imovie.view.filmsdetail.view.DetailPingView;
import com.gykfbxxh.imovie.view.filmsdetail.view.DetailScrollView;
import com.umeng.socialize.UMShareAPI;


/**
 * 影评
 */
@SuppressLint("JavascriptInterface")
public class FilmPingActivity extends BaseActivity implements View.OnClickListener {

    private DetailScrollView mScrollView;//滑动布局
    private CommentListView mCommentListView;//评论载体
    private DetailPingView detailPingView;//内容view
    private LinearLayout ll_rightview;
    private ImageView iv_back,iv_share;
    private TextView tv_comment;
    private String fObjectid;//文章id
    private ImageView iv_tocomment,iv_good,iv_collect;
    private LoadView lv_loadview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //获取传输数据
        mPageName = "FilmPingActivity";
        isInit = false;
        getIntentData();
        super.onCreate(savedInstanceState);
        //加入到影评栈中
        AppManager.getAppManager().addPingActivity(this);
        setContentView(R.layout.activity_film_ping);
        initView();//初始化页面
        loadData();//初始化页面数据
//        querySaveNews();//查询本地收藏
    }

    private void initView() {
        lv_loadview = (LoadView)findViewById(R.id.lv_loadview);
        lv_loadview.setErrorPageClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadData();
            }
        });
        ll_rightview = (LinearLayout) findViewById(R.id.ll_rightview);
        ll_rightview.setVisibility(View.VISIBLE);
        iv_back = (ImageView)findViewById(R.id.iv_back);
        iv_share = (ImageView)findViewById(R.id.iv_share);
        tv_comment = (TextView)findViewById(R.id.tv_comment);
        iv_tocomment = (ImageView)findViewById(R.id.iv_tocomment);
        iv_good = (ImageView)findViewById(R.id.iv_good);
        iv_collect = (ImageView)findViewById(R.id.iv_collect);

        iv_back.setOnClickListener(this);
        iv_share.setOnClickListener(this);
        tv_comment.setOnClickListener(this);
        iv_tocomment.setOnClickListener(this);
        iv_good.setOnClickListener(this);
        iv_collect.setOnClickListener(this);

        this.mScrollView = (DetailScrollView) findViewById(R.id.psv_psrsolview);

        detailPingView = (DetailPingView) findViewById(R.id.dnv_newsview);
        detailPingView.init();
        detailPingView.httpName = mPageName;

        this.mCommentListView = (CommentListView) findViewById(R.id.prlv_listview);

        //配置webview
        configWebView();
    }

    private void getIntentData() {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        fObjectid = intent.getStringExtra(PARAMETER1);
    }

    private void loadData() {
        lv_loadview.showLoadPage("正在努力请求数据...");
        getFilmData();//获取电影信息
    }

    /**
     * 获取电影信息
     */
    private void getFilmData() {
        HttpUtils.addGetRequest(URIContant.GETFILMINFO + fObjectid, new TypeToken<FilmDetailInfo>() {
        }.getType(), mPageName, new HttpListener<FilmDetailInfo>() {
            @Override
            public void onError(VolleyError error) {
                lv_loadview.showErrorPage();
            }

            @Override
            public void onSuccess(FilmDetailInfo response) {
                if(response!=null) {
                    FilmDetailInfo.ResultBean result = response.getResult();
                    if(result!=null&&result.getFilm()!=null&&result.getFilminfo()!=null&&result.getVideoscore()!=null) {
                        lv_loadview.showSuccess();
                        detailPingView.setFilmData(result);

                        //适配评论
                        mCommentListView.setEmptyViewOnClickListener(FilmPingActivity.this);
                        //加载评论
                        mCommentListView.startLoadData(FilmPingActivity.this, fObjectid, mPageName);

                    }else {
                        lv_loadview.showErrorPage();
                    }
                }
            }
        });
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.iv_share:
                share();
                break;
            case R.id.tv_comment://评论窗口
                showCommentDialog();
                break;
            case R.id.iv_tocomment://跳转到评论位置
                swithPage();
                break;
            case R.id.iv_good://点赞
                iv_good.setImageResource(R.drawable.thumbs_f);
                break;
            case R.id.iv_collect://收藏
                iv_collect.setImageResource(R.drawable.collection_f);
                break;
        }
    }

    /**
     * 切换页面
     */
    private void swithPage() {

        if (mScrollView == null || detailPingView == null || !onPageFinish) {
            return;
        }
        if (mScrollView.currentPositon == 0) {
            mScrollView.scrollToSecondView();
            scrollHeadAnimotion(1000);//只要大于webview的y坐标就行
        } else {
            mScrollView.scrollToFirstView();
            scrollHeadAnimotion(detailPingView.getScrollY());
        }
    }


    private Animation enterAnimation;
    private Animation outAnimation;

    /**
     * 滑动头部动画
     *
     * @param t
     */
    private void scrollHeadAnimotion(int t) {
        if (this.detailPingView == null ) {
            return;
        }

        if (t >= this.detailPingView.getWebviewY() ) {

            if (enterAnimation == null) {
                enterAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                        -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
                enterAnimation.setDuration(300);
                enterAnimation.setFillAfter(true);
            }

        } else if (t < this.detailPingView.getWebviewY()) {
            if (outAnimation == null) {
                outAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                        0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                        -1.0f);
                outAnimation.setDuration(300);
                outAnimation.setFillAfter(true);
            }
        }
    }


    private CommentListener mCommentListener;//评论监听
    /* 展示评论框 */
    private void showCommentDialog() {
        if (mCommentListener == null) {
            mCommentListener = new CommentListener() {
                @Override
                public void commentStart() {

                }

                @Override
                public void commentFail(VolleyError volley) {

                }

                @Override
                public void commentSuccess(FilmComment newsComment) {
                    //更新页面
                    if (mCommentListView != null) {
                        mCommentListView.addComment(newsComment);
                    }
                }
            };
        }
        CommentUtils.getInstance().showDialog(this, mPageName, fObjectid, mCommentListener);
    }


    private AppShareUtils mShareUtils;//分享工具
    /**
     * 分享
     */
    private void share() {
        if (mShareUtils == null) {
            mShareUtils = new AppShareUtils(this);
        }
        ShareBean shareBean = null ;
        mShareUtils.showShareDialog(shareBean);
    }

    /* 初始化webview */
    @SuppressLint("SetJavaScriptEnabled")
    private void configWebView() {
        if (detailPingView != null && detailPingView.webview != null && !detailPingView.webview.getIsDestory()) {
            detailPingView.webview.setWebViewClient(new MyWebViewClient());
        }
    }

    // 监听
    private class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (TextUtils.isEmpty(url) || url.length() < 5) {
                return false;
            }

            //判断是否为http协议，如果是自定义协议则交给系统
            String httpStr = "";
            try {
                httpStr = url.substring(0, 4);
            } catch (Exception e1) {
                e1.printStackTrace();
                return false;
            }
            if (!TextUtils.isEmpty(httpStr) && !httpStr.equals("http")
                    && !httpStr.equals("https") && !httpStr.equals("abou")) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(url);
                intent.setData(content_url);
                try {
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            } else if (httpStr.equals("abou")) {
                return true;
            } else {
                if (view != null) {
                    view.loadUrl(url);
                }
                return true;
            }
        }


        @Override
        public void onPageFinished(WebView view, String url) {

            //因为 webview的onPageFinished 会执行两次
            // 所以这里逻辑处理一下 只执行一次
            if (!onPageFinish && !FilmPingActivity.this.isFinishing()) {
                onPageFinish = true;
            }
        }


        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            // progressBar.setVisibility(View.GONE);
            view.goBack();
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

    }

    private boolean onPageFinish;//是否加载成功


    @Override
    protected void onDestroy() {
//        LogUtils.e("gzq", "销毁 当前的activity");
//        CommentUtils.getInstance().dismissDialog();
        setContentView(R.layout.view_null);

        if (this.detailPingView != null) {
            //销毁webview
//            LogUtils.e("gzq", "销毁 当前的View");
            this.detailPingView.destoryWebview();
            this.detailPingView = null;
            this.mCommentListView = null;
        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (this.detailPingView != null) {
            //继续webview
            this.detailPingView.resumeWebview();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (this.detailPingView != null) {
            //暂停webview
            this.detailPingView.stopWebview();
        }
//        int maxMemory = (int) Runtime.getRuntime().maxMemory();
//        int freeMemory = (int)Runtime.getRuntime().freeMemory();
        //检查详情有多少个
        int detailActivityCount = AppManager.getAppManager().getPingActivityCount();
//        LogUtils.e("gzq", "maxMemory = "+maxMemory+"    freeMemory = "+freeMemory);
        if (detailActivityCount > 2) {
//            LogUtils.e("gzq", "detailActivityCount = "+detailActivityCount+"    ___"+this);
            AppManager.getAppManager().finishFirstPingActivity();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            if (detailPingView != null && detailPingView.webview != null
                    && detailPingView.webview.canGoBack()) {
                detailPingView.webview.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if (data != null) {
                UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
